<?php


namespace app\admin\controller;


use app\admin\model\Output;
use app\admin\model\Scheme;
use app\BaseController;
use app\Request;


use think\console\Input;
use think\facade\Config;
use think\facade\Db;
use think\facade\View;

class Bizscheme extends BaseController
{
    /**
     * Bizscheme模型对象
     * @var \app\admin\model\flow\Bizscheme
     */
    protected $model = null;
    protected $scheme = null;
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Bizscheme();
        $this->scheme = new Scheme();
        $schemeId = $this->request->request('ids');
    }


    public function index(Request $request)
    {

        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $request->filter(['strip_tags']);
        $schemeId = $request->request('id');
        $ins = Scheme::find($schemeId);
        if ($request->isAjax()) {
            //获取每页显示的条数
            $limit = $request->param('limit');
            //获取当前页数
            $page = $request->param('page');
            $schemeId = $request->param('scheme_Id');
            $ins = Scheme::find($schemeId);
            //如果发送的来源是Selectpage，则转发到Selectpage
            $dbname = Config::get('database.connections.mysql.database');

            $prefix = Config::get('database.connections.mysql.prefix');
            //从数据库中获取表字段信息
            $sql = "SELECT COLUMN_KEY,COLUMN_NAME,COLUMN_TYPE,COLUMN_COMMENT,COLUMN_DEFAULT FROM `information_schema`.`columns` "
                . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
                . "ORDER BY ORDINAL_POSITION";
            //加载主表的列
            $columnList = Db::query($sql, [$dbname, $ins['bizscheme']]);
            $total = count($columnList);
            $list = $columnList;

            $list = collection($list)->toArray();
            return json(['code' => 200, 'msg' => '', 'total' => $total, 'data' => $list]);
        }
        View::assign('scheme_id', $schemeId);
        View::assign('tableName', $ins['bizscheme']);
        return View::fetch();
    }


    //新增
    public function add(Request $request)
    {
        $schemeId = $request->param('scheme_Id');
        if ($request->isAjax()) {
            $schemeId = $request->param('scheme_id');
            $ins = Scheme::find($schemeId);
            $bizScheme = $ins['bizscheme'];
            $params = $request->param();
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //如果发送的来源是Selectpage，则转发到Selectpage
                    $dbname = Config::get('database.connections.mysql.database');
                    $prefix = Config::get('database.connections.mysql.prefix');

                    //从数据库中获取表字段信息
                    $sql = "SELECT COLUMN_KEY,COLUMN_NAME,COLUMN_TYPE,COLUMN_COMMENT,COLUMN_DEFAULT FROM `information_schema`.`columns` "
                        . "WHERE TABLE_SCHEMA = ? AND table_name = ? and COLUMN_NAME=? "
                        . "ORDER BY ORDINAL_POSITION";
                    //加载主表的列
                    $row = Db::query($sql, [$dbname, $ins['bizscheme'], $params['fieldcode']]);
                    if ($row) {
                        return json(['code' => 400, 'url' => '', 'msg' => '字段已经存在,请更改字段名称']);
                    }
                    $sql = "ALTER TABLE $bizScheme add ( ";
                    switch (strtolower($params['type'])) {
                        case "enum":
                        case "set":
                            $code = explode(',', $params['default']);
                            $res = "";
                            foreach ($code as $l) {
                                $res = $res . "'" . $l . "'" . ",";
                            }
                            $res = rtrim($res, ',');
                            $sql .= ' ' . $params['fieldcode'] . ' ' . $params['type'] . "($res) " . " COMMENT '" . $params['fieldname'] . "',";
                            break;
                        case "datetime":
                            $sql .= ' ' . $params['fieldcode'] . ' ' . $params['type'] . " COMMENT '" . $params['fieldname'] . "',";
                            break;
                        case "int":
                            $defaultvalue = is_numeric($params['default']) == false ? 0 : $params['default'];
                            $sql .= ' ' . $params['fieldcode'] . ' ' . $params['type'] . " default '" . $defaultvalue . "' COMMENT '" . $params['fieldname'] . "',";
                            break;
                        default:
                            $sql .= ' ' . $params['fieldcode'] . ' ' . $params['type'] . " default '" . $params['default'] . "' COMMENT '" . $params['fieldname'] . "',";
                            break;
                    }

                    $sql = rtrim($sql, ',');
                    $sql = $sql . ")";

                    $result = Db::execute($sql);
                    if ($result !== false) {
                        return json(['code' => 200, 'url' => '', 'msg' => '成功！']);
                    } else {
                        return json(['code' => 400, 'url' => '', 'msg' => '失败！']);
                    }

                } catch (\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                }
            }
        }
        View::assign('scheme_id', $schemeId);
        return View::fetch();
    }


    //发布
    public function release(Request $request)
    {
        if ($request->isAjax()) {
            $schemeId = $request->param('scheme_id');
            $ins = Scheme::find($schemeId);

            $bizScheme = strtolower($ins['bizscheme']);
            $flowcode = strtolower($ins['flowcode']);
            $result = null;
            $commandtype = 'FlowCrud';
            $argv = array("--table=$bizScheme", "--controller=flow/$flowcode", "--model=flow/$flowcode");
            array_push($argv, "-force=1");
            $commandName = "\\app\\admin\\command\\" . ucfirst($commandtype);
            $input = new Input($argv);
            $output = new Output();
            $command = new $commandName($commandtype);
            $command->run($input, $output);
            $result = implode("\n", $output->getMessage());
            Db::commit();

            if (strpos($result, 'Successed') == true) {
                $msg = "发布成功";
                Scheme::update([
                    'id' => $schemeId,
                    'isenable' => '1']);
            } else {
                $msg = $result;
            }
            return json(['code' => 200, 'url' => '', 'msg' => $msg]);
        }

    }
}